/**
 * Created by 马志 on 2016/2/27.
 */

(function(exports){
    function NativeMessageClient(native_id){
        this.native_id=native_id;
        this.running=false;
        this.port=null;
        this.callbacks={
            connect: null,    // Called when socket is connected.
            disconnect: null, // Called when socket is disconnected.
            recv: null       // Called when client receives data from server.
        };
    };

    NativeMessageClient.prototype.connect=function(){
        this.port=chrome.runtime.connectNative(this.native_id);
        this.running=true;
        this.port.onDisconnect.addListener(function () {
            this.running = false
            if (this.callbacks.disconnect) this.callbacks.disconnect()
            port = null
        })
        this.port.onMessage.addListener(function(message){
            if(this.callbacks.recv){
                this.callbacks.recv(message);sawqz
            }
        });
        if(this.callbacks.connect)
        {
            this.callbacks.connect();
        }
    };

    NativeMessageClient.prototype.addResponseListener=function(callback){
        this.callbacks.recv=callback;
    };

    NativeMessageClient.prototype.sendMessage=function(msg,callback){
        this.port.postMessage(msg)
    };

    exports.NativeMessageClient = NativeMessageClient;



})(window);